import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getSuggestion, clearSuggestion } from '@/store/actions/search'
// import debounce from 'lodash/debounce'
// import { DebouncedFunc } from 'lodash'
import { useDebounceFn } from 'ahooks'
import { RootState } from '@/types/store'
const GEEK_SEARCH_KEY = 'geek-89-search-history'
const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()

  //输入框的状态
  const [searchTxt, setSearchTxt] = useState('')
  const [searchHistory, setSearchHistory] = useState<string[]>([])

  //防抖
  // const debounceFnRef = useRef<DebouncedFunc<(value: any) => void>>()
  useEffect(() => {
    const localHistory = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? '[]'
    ) as string[]
    setSearchHistory(localHistory)
  }, [])
  const { run: debounceFn } = useDebounceFn(
    (value) => {
      dispatch(getSuggestion(value))
    },
    {
      wait: 500,
    }
  )
  const { suggestion } = useSelector((state: RootState) => state.search)
  //状态控制
  const onSearch = (value: string) => {
    setSearchTxt(value)
    if (value.trim() === '') {
      //输入框为空时，清空数据
      return dispatch(clearSuggestion())
    }
    // dispatch(getSuggestion(value))
    debounceFn(value)
  }
  //关键词高亮
  const highlightSuggestion = suggestion.map((item) => {
    //数据转小写
    const lowerCaseItem = item.toLocaleLowerCase()
    //文本内容转小写
    const lowerCaseSearchTxt = searchTxt.toLocaleLowerCase()
    //是否有这个关键字
    const index = lowerCaseItem.indexOf(lowerCaseSearchTxt)
    //内容长度
    const searchTxtLength = searchTxt.length
    //处理数据结构
    // 左边的
    const left = item.slice(0, index)
    //中间的
    const search = item.slice(index, index + searchTxtLength)
    //右边的
    const right = item.slice(index + searchTxtLength)
    return {
      left,
      right,
      search,
      raw: item,
    }
  })
  const onSearchGo = (value: string) => {
    //清空内容
    dispatch(clearSuggestion())
    //跳转到内容页
    history.push(`/search/result?query=${value}`)
    //把搜索的内容存到本地
    saveHistories(value)
  }
  //历史记录
  const saveHistories = (value: string) => {
    let localHistories = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? '[]'
    ) as string[]

    if (localHistories.length === 0) {
      //没有内容添加
      localHistories = [value]
    } else {
      // 有内容判断，历史记录是否有

      if (localHistories.indexOf(value) > -1) {
        //有，就删除记录的，从新添加到最前面
        const leftHistories = localHistories.filter((item) => item !== value)
        localHistories = [value, ...leftHistories]
      } else {
        localHistories = [...localHistories, value]
      }
    }
    //存到本地
    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(localHistories))
  }
  //删除单个历史记录
  const onDeleteHistory = (value: string) => {
    //取出所有的
    const localHistory = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? '[]'
    ) as string[]
    //删掉点的那个
    const newHistory = localHistory.filter((item) => item !== value)
    //再存回去，并修改状态
    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(newHistory))

    setSearchHistory(newHistory)
  }
  //清空所有的历史记录
  const onClearAllHistory = () => {
    localStorage.removeItem(GEEK_SEARCH_KEY)
    setSearchHistory([])
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span className="search-text" onClick={() => onSearchGo(searchTxt)}>
            搜索
          </span>
        }
      >
        <SearchBar
          placeholder="请输入关键字搜索"
          value={searchTxt}
          onChange={onSearch}
        />
      </NavBar>

      {suggestion.length <= 0 && (
        <div
          className="history"
          style={{
            display: searchHistory.length <= 0 ? 'none' : 'block',
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={onClearAllHistory}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {searchHistory.map((item, index) => (
              <span
                className="history-item"
                key={index}
                onClick={() => onSearchGo(item)}
              >
                <span className="text-overflow">{item}</span>
                <Icon
                  type="iconbtn_essay_close"
                  onClick={() => onDeleteHistory(item)}
                />
              </span>
            ))}
          </div>
        </div>
      )}
      <div
        className={classnames(
          'search-result',
          suggestion.length > 0 ? 'show' : ''
        )}
      >
        {highlightSuggestion.map((item, index) => (
          <div
            className="result-item"
            key={index}
            onClick={() => onSearchGo(item.raw)}
          >
            <Icon className="icon-search" type="iconbtn_search" />
            <div className="result-value text-overflow">
              {item.left}
              <span>{item.search}</span>
              {item.right}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default SearchPage
